﻿using CPPEI.Coolzon.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CPPEI.Coolzon.UI.DataPartLib
{
    public class DataFormatUtil
    {
        /// <summary>
        /// 格式化数据
        /// DOUBLE {0:Nn}
        /// </summary>
        /// <param name="originalValue"></param>
        /// <param name="type"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        public static string ToString(string originalValue, string type, string format)
        {
            originalValue = originalValue.Trim();
            if (!string.IsNullOrEmpty(type) && type.ToUpper() == "DOUBLE")
            {
                if (originalValue.Contains("%"))
                {
                    originalValue = originalValue.Replace("%", string.Empty);
                }
                double dValue = 0;
                if (double.TryParse(originalValue, out dValue))
                {
                    return string.Format(format, dValue);
                }
                return originalValue;
            }

            if (originalValue.StartsWith("."))
            {
                // 前面补0
                string newValue = string.Format("0{0}", originalValue);
                double dValue = 0;
                if (double.TryParse(newValue, out dValue))
                {
                    originalValue = string.Format("{0:N2}", dValue);
                }
            }
            else if (originalValue.StartsWith("-."))
            {
                // 前面补0
                string newValue = originalValue.Replace("-.", "-0.");
                double dValue = 0;
                if (double.TryParse(newValue, out dValue))
                {
                    originalValue= newValue;
                }
            }
            if (!string.IsNullOrWhiteSpace(format))
            {
                double nValue = 0f;
                if (double.TryParse(originalValue.Replace("%", ""), out nValue))
                {
                    if (originalValue.IndexOf("%") != -1)
                    {
                        originalValue = (Convertor.ToDouble(originalValue.Replace("%", "")) / 100).ToString(format);
                    }
                    else
                    {
                        originalValue = Convertor.ToDouble(originalValue).ToString(format);
                    }
                }
            }
            return originalValue;
        }
    }
}
